package flinkSql.window.over;

import bean.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Over;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.junit.Test;

import static org.apache.flink.table.api.Expressions.$;

//TODO 处理时间会话窗口
public class Flink_ProcessTime_overWindow {

    @Test
    public void test() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<SensorReading> input = env.socketTextStream("node193", 9999)
                .map((MapFunction<String, SensorReading>) value -> {
                    String[] split = value.split(",");
                    return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
                });

        Table table = tableEnvironment.fromDataStream(input, $("id"), $("ts"), $("temp"), $("pt").proctime());

        Table select = table.window(Over.partitionBy("id").orderBy($("pt")).preceding("10.seconds").as("ss"))
                .select("id,id.count over ss");

        tableEnvironment.createTemporaryView("sqlTable",table);
        Table sqlResult = tableEnvironment.sqlQuery("select id,sum(temp) over(partition by id order by pt) ct from sqlTable");

        tableEnvironment.toAppendStream(sqlResult,Row.class).print("table");

        env.execute();


    }
}
